<template>
  <div class="budgetBox">
    <table border="1px solid rgba(212, 232, 228, 0.73)" cellspacing="0">
      <thead>
        <tr class="title">
          <th>经费投入预算</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr class="label">
          <td>科目</td>
          <td>金额（万元）</td>
        </tr>
        <tr v-for="(item,index) in data.table1" :key="index" >
          <td>{{ item.subjectName }}</td>
<!--          <td><input type="number" v-model="item.amount" :readonly="addFlag == 2" maxlength="11"/></td>-->
          <td><input v-model="item.amount" :readonly="addFlag == 2"
                     maxlength="14"
                     type="number"
                     :onkeypress="() => limitDecimalDigits(item, 1)"  /></td>
        </tr>
        <tr>
          <td>合计</td>
          <td><input disabled type="text" min="0" v-model="data.totalNum1" placeholder="自动计算" /></td>
        </tr>
      </tbody>
    </table>

    <table border="1px solid rgba(212, 232, 228, 0.73)" cellspacing="0">
      <thead>
        <tr class="title">
          <th>经费支出预算</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr class="label">
          <td>科目</td>
          <td>金额（万元）</td>
        </tr>
        <tr v-for="(item,index) in data.table2" :key="index" >
          <td>{{ item.subjectName }}</td>
          <td><input  v-model="item.amount" :readonly="addFlag == 2"
                     maxlength="14"
                      type="number"
                      :onkeypress="() => limitDecimalDigits(item, 1)"  /></td>
        </tr>
        <tr>
          <td>合计</td>
          <td><input disabled type="text" min="0" v-model="data.totalNum2" placeholder="自动计算" /></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import tableJson from './budegetTable.json'

export default {
  props:{
    fatherTableJson:{
      type:Array,
    },
    addFlag:{
      type:Number,
    }
  },
  setup(props, { emit }) {
    const input = ref()
    const data = reactive({
      table1:[{subjectName:'',amount:''}],
      table2:[{subjectName:'',amount:''}],
      totalNum1:0,
      totalNum2:0,
    })
    const fatherTableJson:any = props.fatherTableJson
    //分开table数据
    const hadTable = () =>{
      data.table1 = []
      data.table2 = []
      // data.totalNum1 = 0
      data.totalNum2 = 0
      // if(props.fatherTableJson?.length){
        if(props.addFlag != 0){
        Object.assign(tableJson.contractBudgetList, props.fatherTableJson);
        // props.fatherTableJson?.forEach((e:any) =>{
          console.log('编辑',tableJson,props.fatherTableJson);
          tableJson.contractBudgetList.forEach((e:any) =>{
          if(e.costCategory == '1'){
            // data.totalNum1 += parseInt(e.amount)
            data.table1.push(e)
          }else{
            data.table2.push(e)
            data.totalNum2 += parseInt(e.amount)
            // let flat: number[] = [];
            // e.forEach((item) => {
            //   if (item.length) flat = flat.concat(item.map(item.amount));
            // });
            // return flat.length ? flat.reduce((now, next) => {
            //   const num1Len = (now.toString().split('.')[1])?.length || 0;
            //   const num2Len = (next.toString().split('.')[1])?.length || 0;
            //   const maxLen = Math.pow(10, Math.max(num1Len, num2Len));
            //   return (Math.round(now * maxLen) + Math.round(next * maxLen)) / maxLen
            // }, 0) : 0;
          }
        })
      }else{
        tableJson.contractBudgetList = [
          {
            "costCategory":"1",
            "costCategoryName":"费用投入",
            "subject":"1",
            "subjectName":"中交集团外拨款",
            "amount":"0"
          },
          {
              "costCategory":"1",
              "costCategoryName":"费用投入",
              "subject":"2",
              "subjectName":"中交集团拨款",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"直接费用",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"4",
              "subjectName":"研究人员费用",
              "amount":"0"
          },
          {
              "costCategory":"1",
              "costCategoryName":"费用投入",
              "subject":"2",
              "subjectName":"中咨集团拨款",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"设备费",
              "amount":"0"
          },
          {
              "costCategory":"1",
              "costCategoryName":"费用投入",
              "subject":"2",
              "subjectName":"承担单位拨款",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"购置设备费",
              "amount":"0"
          },
          {
              "costCategory":"1",
              "costCategoryName":"费用投入",
              "subject":"2",
              "subjectName":"协作单位拨款",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"试制设备费",
              "amount":"0"
          },
          {
              "costCategory":"1",
              "costCategoryName":"费用投入",
              "subject":"2",
              "subjectName":"设备改造与租赁费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"材料费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"2",
              "subjectName":"测试化验加工费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"燃料动力费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"差旅/会议/国际合作与交流费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"出版/文献/信息传播/知识产权事务费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"劳务费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"专家咨询费",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"其他支出",
              "amount":"0"
          },
          {
              "costCategory":"2",
              "costCategoryName":"费用支出",
              "subject":"3",
              "subjectName":"间接费用",
              "amount":"0"
          }
        ]

        tableJson.contractBudgetList.forEach(e =>{
          // console.log('新增 tableJson',tableJson);
          if(e.costCategory == '1'){
            // data.totalNum1 += parseInt(e.amount)
            data.table1.push(e)
          }else{
            data.table2.push(e)
            data.totalNum2 += parseInt(e.amount)
          }
        })
      }


    }
    onMounted(() => {
      hadTable()
    });
    const limitDecimalDigits = (item: any, n: number) => {
      const regex = new RegExp(`^(\\d+\\.\\d{0,${n}}|\\d*)$`);
      return regex.test((item.amount ?? '').toString())
    }
    const calcNumber = (arr: Record<string, any>[]): number => {
      return arr.length ? arr.reduce((now, next) => {
        const nextNum = +next.amount || 0;
        const num1Len = (now.toString().split('.')[1])?.length || 0;
        const num2Len = (nextNum.toString().split('.')[1])?.length || 0;
        const maxLen = Math.pow(10, Math.max(num1Len, num2Len));
        return (Math.round(now * maxLen) + Math.round(nextNum * maxLen)) / maxLen
      }, 0) : 0;
    }
    watch(() => data.table1, (newValue, oldValue) => {
      emit('tableJson', tableJson)
      // console.log('table1',data.table1);
      // data.totalNum1 = 0
/*      data.table1.forEach(e =>{
        data.totalNum1 += Number(e.amount)
      })*/
      data.totalNum1 = calcNumber(data.table1)

    },{deep: true})

    watch(() => data.table2, (newValue, oldValue) => {
      emit('tableJson', tableJson)
      // console.log('table2',data.table2);
      // data.totalNum2 = 0
      // data.table2.forEach(e =>{
      //   data.totalNum2 += Number(e.amount)
      // })
      data.totalNum2 = calcNumber(data.table2)

    },{deep: true})
    watch(() => props.addFlag, (newValue, oldValue) => {
      hadTable()
    },{deep: true})

    return {
      input,
      hadTable,
      data,
      fatherTableJson,
      limitDecimalDigits,
    }
  },
}
</script>

<style scoped lang="scss">
table {
  line-height: 24px;
  margin: 20px auto;
}
th{
  height: 25px;
}
.title {
  text-align: center;
  line-height: 36px;
  background-color: #f0f2f5;
  th {
    width: 200px;
  }
  th:nth-child(3) {
    width: 250px;
  }
}
.label {
  text-align: center;
  line-height: 28px;
}

input {
  outline: none;
  width: 90%;
  margin: 0 5%;
}
.budgetBox{
  display: flex;
}
</style>
